package com.affectu.search.fetch;

import java.util.Date;

import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.filters.OrFilter;
import org.htmlparser.tags.BulletList;
import org.htmlparser.tags.Div;
import org.htmlparser.tags.Span;
import org.htmlparser.util.NodeList;

import com.affectu.search.Spider;
import com.affectu.search.fetch.thread.OutTaskThread;
import com.affectu.task.OuterTask;

/**
 * Oct 15, 2008
 * 
 * @author daniel nathan
 */
public class Zhubajie extends OutTaskThread {

	private Spider spider = new Spider();

	public Zhubajie() {
		super("http://www.zhubajie.com/", "/task/iv/");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.affectu.search.fetch.task.FetchThread#spideSubpage(java.lang.String)
	 */
	@Override
	public OuterTask spideSubPage(String url) {
		OuterTask outTask = new OuterTask();
		String name = "";
		String tag = "";
		int budget = 0;
		String description = "";
		try {
			OrFilter allFilter = new OrFilter();
			allFilter.setPredicates(new NodeFilter[] {
					new NodeClassFilter(Div.class),
					new NodeClassFilter(Span.class),
					new NodeClassFilter(BulletList.class) });
			NodeList nodeList = new Parser(url).parse(allFilter);
			for (Node node : nodeList.toNodeArray()) {

				String attributeValue;
				if (node instanceof BulletList) {
					BulletList divNode = (BulletList) node;

					attributeValue = divNode.getAttribute("class");
					if ("task_details_left".equals(attributeValue)) {
						String values = divNode.toPlainTextString();
						String value = spider.fetchSpecificText(
								"价格：￥[\\s\\S]*\\s*任务编号", values).trim();
						budget = this.getIntValue(value);
						this.log("budget:" + values);
					}

				} else if (node instanceof Div) {
					Div divNode = (Div) node;
					attributeValue = divNode.getAttribute("class");
					if ("title".equals(attributeValue)) {
						// ...得到新闻标题(纯文本)
						name = divNode.toPlainTextString();
						this.log("name:" + name);
					}
					if (attributeValue != null
							&& attributeValue.indexOf("task_content") > -1) {
						// ...得到内容(纯文本)
						description = divNode.toHtml();
						this.log("description:" + description);
					}
					if ("inurl".equals(attributeValue)) {
						int toIndex = divNode.toPlainTextString().lastIndexOf(
								">");
						tag = divNode.toPlainTextString()
								.substring(16, toIndex);
						this.log("tag:" + tag);
					}
				}
			}// end for
			outTask.setId(System.currentTimeMillis());
			outTask.setName(name);
			outTask.setTag(tag);
			outTask.setBudget(budget);
			outTask.setDescription(description);
			outTask.setUrl(url);
			outTask.setPublishDate(new Date());

		} catch (Exception ex) {
			this.logAffectuException(ex, "");
		}
		return outTask;
	}

}
